dojo.provide("slipstream.view.MDEditor");
dojo.require("slipstream.layout._TemplatedLayoutWidget");
dojo.require("dijit._Container");
dojo.require("dijit.Editor");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dojox.grid.DataGrid");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dojox.form.MultiComboBox");
dojo.require("dojox.layout.ExpandoPane");
dojo.require("dojo.date.locale");
dojo.require("dijit._editor.plugins.FontChoice");
dojo.require("dijit._editor.plugins.LinkDialog");

dojo.declare("slipstream.view.MDEditor",
	[slipstream.layout._TemplatedLayoutWidget], {
		
	
	forms: null,
	slugsource: null,
	store: null,
	autosave: false,
	structure: null,
	activeItem: null,
	formConnections: null,
	widgetsInTemplate: true,
	doLayout: true,
	baseClass: "dijitContentPane",
	isDebug: false,
	prefix: '',
	suffix: '',
	uploaddir: '/images/',
	createElement: false,
	meta: null,
	language: 'sv',
	
	constructor: function(args){
		this.log('Constructing MDEditor for '+args.title,args);
		this.cnx={};
		this.cnx.slugsource=new dojo.NodeList();
		this.cnx.forms=new dojo.NodeList();
		this.forms=new dojo.NodeList();
		this.lang=new dojo.NodeList();
		this.slugsource=new dojo.NodeList();
		this.postLayout=new dojo.NodeList();
		this.buttons={};
		this.languageOptions={};
		this.langMenu=undefined;
		//this.detailSwitch=undefined;
	},
	
	postMixInProperties: function(){
		this.log('postMixInProperties for '+this.title);
	},
	buildRendering: function(){
		console.group('slipstream.view.MDEditor::buildRendering for '+this.title);
		this.inherited(arguments);
		this.log('done');
		console.groupEnd();
	},
	postCreate: function(){
		this.log('postCreate for '+this.title);
		//this.log('post create');
		this.inherited(arguments);
		//if (this.meta instanceof Array) console.log(this.meta,'Meta');
		this.isLoaded=true;
		if (this.grid) {
			//if(this.model && !this.grid.model) this.grid.setStore(this.store);
		this.log(this.store===this.grid.store? 'true':'false');
		this.log('pre?');
		this.log('post?');
		//this.log(this.store===this.grid.store? 'true':'false');
			dojo.connect(this.grid, 'onRowClick', this, '_onGridClick');
		}
		if(this.itemtype){
			//console.log('Copnnecting itemtype');
			dojo.connect(this.itemtype, 'onChange', this, '_onMetaChange');
		}
		if(this.metaPane){
			//this.metaPane.onDownloadEnd=dojo.hitch(this,function(){this._setMetaForm()});
			dojo.connect(this.metaPane, 'onDownloadEnd', this, '_setMetaForm');
		}
		if(this.tree) dojo.connect(this.tree, 'onClick', this, '_onTreeClick');
		var self=this;
		if(!this.autoSave && this.buttonBar){
			this.buttons.save = new dijit.form.Button({
				label: "Spara",
				style: "float: left",
				disabled: true,
				onClick: dojo.hitch(this,function(e){
					this._forceValuesToStore();
					if(this.store.isDirty()){this.store.save()};
					//console.debug(this.item);
				})
			});
			this.buttons.revert = new dijit.form.Button({
				label: "Återställ",
				disabled: true,
				onClick: dojo.hitch(this,function(e){
					this.store.revert();
					this._setItemAttr(this.item);
				})
			});
			this.buttonBar.domNode.appendChild(this.buttons.save.domNode);
			this.buttonBar.domNode.appendChild(this.buttons.revert.domNode);
			this.slugsource.attr('intermediateChanges',true);
		};
		if(this.imageButton){
			this.buttons.image=this.imageButton;
			//console.debug(this.buttons.image);
			this.postLayout.push(dojo.hitch(this,function(){
				this.imageUpload=new dojox.form.FileUploader({
					uploadUrl: this.uploaddir+'UploadFile.php',
					selectMultipleFiles: false,
					button: this.buttons.image,
					isDebug: true,
					onChange: dojo.hitch(this,function(files){
						//files[0].name='staff_'+this.store.getValue(this.item,'idstaff')+files[0].type;
						//this.log('Selected files',files);
						//this.log('postdata',this.imageUpload.postData);
						var fileName=this.prefix+this.store.getValue(this.item,this.store.getIdentityAttributes()[0])+this.suffix+files[0].type;
						
							//console.log('Uploading: ',fileName)
						this.imageUpload.upload({name:(fileName)});
						//dojo.connect(this.imageUpload,'onComplete',this,'_reloadImage');
						dojo.connect(this.imageUpload,'onComplete',this,function(){
							//set name here
							this.image.src=(this.uploaddir+fileName+'?'+(new Date().toString()));
							//console.log('Setting filename: ',fileName);
							if(this.store.hasAttribute(this.item,'img')) this.store.setValue(this.item,'img',fileName);
						});
						//setTimeout(dojo.hitch(this, "_reloadImage"), 200);
						//this.image.src=(this.image.src+'?'+Math.ceil(Math.random()*10000));
						//this.image.src='/images/staff_'+this.store.getValue(this.item,'idstaff')+files[0].type;
					})
				});
			}))
			/*this.imageUpload=new dojox.form.FileUploader({
				uploadUrl: '/images/UploadFile.php',
				button: this.buttons.image,
				isDebug: true
			});*/
		}
		this.buttons.create = new dijit.form.Button({
			label: "Skapa ny",
			disabled: !this.createElement,
			onClick: dojo.hitch(this,function(e){
				this._storeSaveRollback();
				this._clearForms();
				/*if(this.store.ss_settings.i18n==true){
					
				}*/
				var newitem=this.store.newItem(this.skeleton?dojo.clone(this.skeleton):{Translation:{en:{},sv:{}}});
				this.log('New Item:',newitem);
				this._setItemAttr(newitem);
			})
		});
		this.buttonBar.domNode.appendChild(this.buttons.create.domNode);
		if(this.languageOptions && this.buttonBar){
			this.langMenu=new dojox.form.DropDownSelect({
				disabled: true,
				onChange: dojo.hitch(this,function(lang){
					console.log('onSelect',lang);
					if(lang) this.setLang(lang);
				})
			},dojo.create('select'));
			this.langMenu.addOption(this.languageOptions);
			console.log(this.langMenu,'Created Language menu');
			this.buttonBar.domNode.appendChild(this.langMenu.domNode);
		};
		//if(this.store!==undefined && this.grid.store===null) this.log('Setting grid',this.grid.setStore(this.store,{},{cache:true}));
	},
	
	layout: function(){
		this.log('layout');
		if(this.grid && this.store!==undefined && this.grid.store===null) this.log('Setting grid',this.grid.setStore(this.store,{},{})); //cache:true
		var cb=this._contentBox;
		if(this.getChildren().length==1){
			this.getChildren()[0].resize({h:cb.h,w:cb.w});
		} else {
			console.error('Can only contain one child, have '+this.getChildren().length,this);
		}
		this.postLayout.forEach(dojo.hitch(this,function(obj){obj()}))
	},
	_reloadImage: function(){
		this.image.src=(this.image.src+'?'+(new Date().toString()));//+Math.ceil(Math.random()*10000));
		//this.image.src=(this.uploaddir+this.image.src+'?'+(new Date().toString()));//+Math.ceil(Math.random()*10000));
		//this.imageUpload.upload({name:(this.prefix+this.store.getValue(this.item,this.store.getIdentityAttributes()[0])+this.suffix+files[0].type)});
	},
	_onGridClick: function(e){
		this.log('Grid click',e);
		//this.log('Dirty before',this.store.isDirty());
		this._storeSaveRollback();
		this.log('Index',e.rowIndex);
		var item=e.grid.getItem(e.rowIndex);
		this.log('Item',item);
		this.log('Grid',e.grid);
		this.resetLang();
		this.store.loadItem({
			item: item,
			onItem: dojo.hitch(this, "_setItemAttr"),
		});
		this.browse.toggle();
		if(!this.detail._showing) this.detail.toggle();
	},
	_onTreeClick: function(item,node){
		this.log('Tree click',item,node);
		this._storeSaveRollback();
		this._setItemAttr(item);
		this.browse.toggle();
		if(!this.detail._showing) this.detail.toggle();
		//this.log('Dirty before',this.store.isDirty());
		/*this._storeSaveRollback();
		this.store.loadItem({
			item: e.grid.getItem(e.rowIndex),
			onItem: dojo.hitch(this, "_setItemAttr"),
		});
		this.browse.toggle();
		if(!this.detail._showing) this.detail.toggle();*/
	},
	_getSlugSourceValue: function(){
		return this.slugsource.map(function(obj){return obj.attr('value')}).join(' ');
	},
	
	_clearForms: function(){
		this.cnx.slugsource.forEach(function(obj){dojo.disconnect(obj)});
		this.cnx.slugsource.length=0;
		this.cnx.forms.forEach(function(obj){dojo.disconnect(obj)});
		this.cnx.forms.length=0;
		//this.forms.attr('value','');
		this.forms.forEach(function(obj){obj.reset?obj.reset():obj.attr('value','')});
		//this.log(this.forms);
	},
	
	_setupMetaEditor: function(){
		//console.log(this.store.getValue(this.item, 'class_editor'), 'Extra editor');
		this.metaPane.attr('href','/lib/site/view/meta/'+this.store.getValue(this.item, 'class_editor')+'.html');
	},
	
	_onMetaChange: function(type){
		//console.log('Meta type',type);
		this.metaPane.attr('href','/lib/site/view/meta/structure_meta_'+type+'.html');
	},
	
	_setMetaForm: function(){
		this.meta=new dojo.NodeList();
		var nodes=dojo.query('.meta_input_form',this.metaPane.domNode);
		//console.log(nodes);
		nodes.forEach(dojo.hitch(this,function(node){
			var obj=dijit.byNode(node);
			//console.log('processing',obj);
			this.meta.push(obj);
			//console.log(this.store);
			if(this.store.hasAttribute(this.item,obj.name)){
				//console.log('Setting value for',obj.name);
				obj.attr('value',this.store.getValue(this.item,obj.name));
			} else {
				//console.log('Creating value for',obj.name);
				this.store.setValue(this.item,obj.name,obj.attr('value'));
			}
		}));
		//console.log(this.meta);
	},
	
	getImageSrc: function(){
		return this.uploaddir+this.prefix+this.store.getValue(this.item,this.store.getIdentityAttributes()[0])+this.suffix+'.jpg';
	},
	
	_setItemAttr: function(item){
		this.log('Setting item',item);
		//this.log('Forms',this.forms);
		this._clearForms();
		this.detailSwitch.selectChild(this.edit);
		this.item=item;
		/*if(this.item.Translation!=undefined){
			if(this.item.Translation[this.lang]==undefined)this.store.setValue(this.item,Translation[this.lang]={};
		}*/
		/*if (this.metaPane && ((type=this.store.getValue(this.item, 'itemtype_iditemtype')) !== null)) {
			this._onMetaChange(type);
		}*/
		if(this.image) this.image.src=this.getImageSrc();
		var store=this.store;
		this.forms.forEach(dojo.hitch(this,function(obj){
			if(this.store.hasAttribute(this.item,obj.name)){
				if((value=store.getValue(this.item,obj.name))!=null){
					//this.log(obj.name+': '+store.getValue(item,obj.name));
					//obj.attr('value',this.store.getValue(this.item,obj.name));
					//if(dojo.isObject(value)) console.log('Value is object')
					if(dojo.isObject(value)&&value._loadObject){
						//console.log(value,'Object needs loading')
					}
					//console.log(value,obj,'MDE setting value')
					obj.attr('value',value);
				}
				this.cnx.forms.push(dojo.connect(obj,"onChange",function(){
					store.setValue(item,obj.name,obj.attr('value'));
				}));
			} else if(obj.name.indexOf('meta_')>-1){
				//console.log('Found meta attribute',obj.name)
			}
			
		}));
		if ((this.slugsource.length>0) && this.slug) {
			if ((this.slug.attr('value') == '') || (this.slug.attr('value') == convertToSlug(this._getSlugSourceValue()))) {
				this.slugsource.forEach(dojo.hitch(this,function(obj){
					this.cnx.slugsource.push(dojo.connect(obj, 'onChange', this, function(e){
						this.slug.attr('value', convertToSlug(this._getSlugSourceValue()));
					}));
				}));
			}
			this.cnx.forms.push(dojo.connect(this.slug, "onChange", this, function(){
				if (this.slug.attr('value') == '') {
					this.slug.attr('value', convertToSlug(this._getSlugSourceValue()));
					if (this.cnx.slugsource.length==0) {
						this.log(this.slugsource);
						this.slugsource.forEach(dojo.hitch(this,function(obj){
							this.cnx.slugsource.push(dojo.connect(obj,'onChange',this,function(e){
								this.slug.attr('value', convertToSlug(this._getSlugSourceValue()));
							}))
						}));
					}
				}
				else 
					if (this.slug.attr('value') != convertToSlug(this._getSlugSourceValue())) {
						dojo.forEach(this.slugConnection,function(obj){dojo.disconnect(obj)});
					}
			}))
		}
		this.buttons.save.attr('disabled',false);
		this.buttons.revert.attr('disabled',false);
		this.langMenu.attr('disabled',false);
	},
	
	_onChangeSlug: function(){
		if(this.slug.attr('value')=='') this.slug.attr('value',convertToSlug(this._getSlugSourceValue()));
	},
	
	_forceValuesToStore: function(){
		if (this.item) {
			dojo.forEach(this.forms, function(node){
				_node=node.attr('value');
				_store=this.store.getValue(this.item, node.name);
				if(_node instanceof Date){
					//console.log('isdate',!(dobj=this.store.getValue(this.item, node.name) instanceof Date),this.store.getValue(this.item, node.name));
					if ((!((dobj=_store) instanceof Date)) || (dobj.getTime() != _node.getTime())) {
						this.log('Changed date node '+node.name);
						this.store.setValue(this.item, node.name, _node);
					}
				} else if(dojo.isArray(_node) && dojo.isArray(dobj=_store)){
					if(!dojo.every(_node,function(i,idx){return i===dobj[idx]})){
						this.log('Changed object node ',node.name,'to',_node,'from',_store);
						this.store.setValue(this.item, node.name, _node);
					}
				} else if(((typeof(_node)==='string') && (_node.length==0)) && (typeof(_store)==='undefined'||_store===null)){
				} else {
					if (_store != _node) {
						this.log('Changed string node ',node.name,'to',"'"+_node+"'",'from',"'"+_store+"'");
						this.log('Eval '+node.name+': ',(_node===_store?'true':'false'));
						this.store.setValue(this.item, node.name, _node);
					};
				};
			}, this);
			this.onSave();
		}
	},
	
	resetLang:function(){
		this.store.lang=this.language;
		if(this.langMenu) this.langMenu.attr('value',this.language);
	},
	
	setLang: function(lang){
		if(this.store.lang != lang){
			this.store.lang=lang;
			this._setItemAttr(this.item);
		}
		/*
		this.language=lang;
		this.lang.forEach(function(item){
			console.log(item);
			if(item[store]) item.store.lang=lang;
		})
		*/
	},
	
	_storeSaveRollback: function(){
		this.log('Dirty before',this.store.isDirty());
		this._forceValuesToStore();
		this.log('Dirty after',this.store.isDirty());
		if(this.store.isDirty()){
			if(confirm('Vill du spara dina ändringar?')){
				this.store.save();
			} else {
				this.store.revert();
			}
		}
		this.log('Dirty after s/r',this.store.isDirty());
	},
	
	saveComplete: function(){
		ss_error::warn('Good save');
	},
	
	saveError: function(e){
		ss_error::warn('Error While saving',e);
	},
	
	log: function(){
		if (this.isDebug) {
			console.log.apply(console, arguments);
		}
	},
	
	getValueAttr: function(){
		return this.item;
	},
	
	onSave: function(){
		
	}
});
